package com.example.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.exception.ServiceException;

import java.util.Date;

public class JwtUtil {
    private static final String SECRET = "yxk.org.test";
    private static final long EXPIRATION_TIME = 10 * 60 * 1000; // 10分钟

    /**
     *
     * @param data  生成token的数据
     * @return  token
     */
    public static String createToken(String data) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + EXPIRATION_TIME);

        return JWT.create()
                .withSubject(data)
                .withIssuedAt(now)
                .withExpiresAt(expiryDate)
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     *
     * @param data  生成token的数据
     * @param minute    过期时间，分钟
     * @return  token
     */
    public static String createToken(String data, Integer minute) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + minute * 60 * 1000);

        return JWT.create()
                .withSubject(data)
                .withIssuedAt(now)
                .withExpiresAt(expiryDate)
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 验证并解析JWT token
     *
     * @param token 要验证的token字符串
     * @return 解码后的JWT对象
     * @throws JWTVerificationException 如果token无效或过期
     */
    private static DecodedJWT verifyToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            return verifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ServiceException(ResultCodeUtil.VALIDATION_ERROR);
        }

    }

    /**
     *
     * @param token 需要验证的token字符串
     * @return  token有效并解析token的字符串
     */
    public static String verify(String token) {
        DecodedJWT jwt = verifyToken(token);
        return jwt.getSubject();
    }
}
